package com.fluxtool.utill.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.fluxtool.entity.AuthenticationVo;
import com.fluxtool.entity.RoleVo;
import com.fluxtool.entity.UserVo;
import com.fluxtool.service.IUserService;

public class AuthRealm extends AuthorizingRealm {

	@Autowired
	private IUserService userService;
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		UserVo user=(UserVo) principal.fromRealm(this.getClass().getName()).iterator().next();//获取session中的用户
        List<String> permissions=new ArrayList<>();
        List<RoleVo> roles = user.getRoles();
        if(roles.size()>0) {
            for(RoleVo role : roles) {
                List<AuthenticationVo> authentications = role.getAuthentications();
                if(authentications.size()>0) {
                    for(AuthenticationVo authentication : authentications) {
                        permissions.add(authentication.getAuthentication());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);//将权限放入shiro中.
        return info;
	}

	/**
	 *用户验证 
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken utoken=(UsernamePasswordToken) token;//获取用户输入的token
        String username = utoken.getUsername();
        UserVo user = userService.findByUserName(username);
        return new SimpleAuthenticationInfo(user, user.getPassword(),this.getClass().getName());
        //放入shiro.调用CredentialsMatcher检验密码
	}

}
